import { SocketClient } from "@/plugins/socket";
import voice from "@/assets/voice/notice.mp3";
import { request } from "@/utils/request";
import { useRepairStore } from "@/store/modules/repair";

const setupNotice = () => {
  //定义websocket连接
  //   首先获取一下当前用户的角色信息
  let rolesStr = localStorage.getItem("roles");
  if (rolesStr) {
    let rolesData = JSON.parse(rolesStr);
    const values = rolesData.map((item) => item.value);
    if (!values.some((i) => i == "class_role")) {
      return;
    }
  } else {
    return;
  }

  // 使用示例
  //音频播放
  // 用于获取音频播放授权的函数
  let hasAudioPermission = false;
  function requestAudioPermission() {
    return navigator.mediaDevices
      .getUserMedia({ audio: true })
      .then(() => {
        hasAudioPermission = true;
        console.log("音频播放OK");
      })
      .catch((err) => {
        console.error("获取音频播放授权失败:", err);
      });
  }

  // 初始化函数，检查并获取授权（页面加载时调用）
  async function init() {
    try {
      await requestAudioPermission();
    } catch (err) {
      // 如果授权失败，可以考虑提示用户手动操作或者采取其他备用方案等
      console.log("初始化授权出错，可能无法正常播放音频提醒");
    }
  }
  init();
  const onReceive = (data) => {
    let clientData = JSON.parse(data);
    let clientID = clientData.data.clientId;
    if (clientData.code == 0) {
      //绑定分组
      bindToGroup(clientID);
    }
    if (clientData.code == 5001) {
      const repairStore = useRepairStore();
      repairStore.addRepairs(JSON.parse(clientData.data));
      playVoice();
    }
  };
  const playVoice = () => {
    //新订单通知消息
    let audio = new Audio(voice);
    // 加载完成后开始播放
    audio.addEventListener("loadeddata", () => {
      audio.play();
    });
  };
  const bindToGroup = async (clientID) => {
    await request("api/bind_to_group", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      data: {
        clientId: clientID,
        groupName: "class_role",
        userId: "1",
        extend: "",
      },
    });
  };
  const onErrorEvent = (data) => {
    console.log("onErrorEvent", data);
  };

  const onErrorSucceed = (data) => {
    console.log("onErrorSucceed", data);
  };
  const baseUrl = `${import.meta.env.VITE_BASE_API_URL}`;
  const protocol = import.meta.env.MODE === "development" ? "ws" : "wss";
  const host = baseUrl.replace("http://", "");
  console.log(protocol);
  const socketUrl = `${protocol}://${host}/ws?systemId=1`; // 替换为实际的WebSocket服务器地址

  const webSocketClient = new SocketClient(
    socketUrl,
    onReceive,
    onErrorEvent,
    onErrorSucceed,
    "1"
  );
};

export { setupNotice };
